Ext.require(['*']);

Ext.define('itemModel2', {
	extend: 'Ext.data.Model',
	fields: [
		{name: 'nombreItem',     type: 'string'},
		{name: 'idItem',     type: 'int'},
		{name: 'codItem', type: 'string'},
		{name: 'complejidadItem', type: 'string'},
		{name: 'descripcionItem', type: 'string'},
		{name: 'idTipoItem', type: 'string'},
		{name: 'nombreTipoItem', type: 'string'},
		{name: 'versionItem', type: 'string'},
		{name: 'estadoItem', type: 'string'},
		{name: 'revisarItem', type: 'boolean'},
	]
});

Ext.define('lineabaseModel', {
	extend: 'Ext.data.Model',
	fields: [
		{name: 'idLineaBase',     type: 'int'},
		{name: 'nro_items',     type: 'int'},
		{name: 'estado', type: 'string'},
		{name: 'fecha_creacion', type: 'string'},
	]
});

Ext.define('GesLineasBaseLiveSearchGridPanel', {
    extend: 'Ext.ux.LiveSearchGridPanel',
    
    initComponent: function() {
        
        //Ext.Msg.alert('Estoy en el initComponet del live!!!');
        var me = this;
        me.tbar = ['Buscar',{
                 xtype: 'textfield',
                 name: 'searchField',
                 hideLabel: true,
                 width: 200,
                 listeners: {
                     change: {
                         fn: me.onTextFieldChange,
                         scope: this,
                         buffer: 100
                     }
                 }
            }, {
                xtype: 'button',
                text: '<',
                tooltip: 'Anterior',
                handler: me.onPreviousClick,
                scope: me
            },{
                xtype: 'button',
                text: '>',
                tooltip: 'Siguiente',
                handler: me.onNextClick,
                scope: me
            }, '-', {
                xtype: 'checkbox',
                hideLabel: true,
                margin: '0 0 0 4px',
                handler: me.regExpToggle,
                scope: me                
            }, 'Expresión Regular', {
                xtype: 'checkbox',
                hideLabel: true,
                margin: '0 0 0 4px',
                handler: me.caseSensitiveToggle,
                scope: me
            }, 'Detectar Mayúsculas'];
        
        me.callParent(arguments);
    }
});

Ext.define('App.view.GesLineasBase', {
	extend: 'Ext.panel.Panel',
    alias: 'widget.tabfirst',
	layout:'anchor',
	
	initComponent: function () {
		this.myIdFase = idFaseAux;
        this.myNombreFase = nombreFaseAux;
        this.myNombreProyecto = nombreProyectoAux;
        
        //creamos varibales para que los IDs no entren en conflicto
		this.idBtonCrearLineaBase = 'btn_grid_crear_lineabase' + this.myIdFase;
		this.idBtonRomperLineaBase = 'btn_grid_romper_lineabase' + this.myIdFase;
		this.idBtonVerItemsLineaBase = 'btn_grid_veritems_lineabase' + this.myIdFase;
		
		this.store = Ext.create('Ext.data.Store', {
			storeId: 'lineasbaseStore',
			model: 'lineabaseModel',
			proxy: {
				type: 'ajax',
				url: '/lineas_base/view',
				reader: {
					type: 'json',
					root: 'lineas_base'
				}
			},
			idFase: this.myIdFase,
			autoLoad: {start: 0, limit: 25, params:{idFase: this.myIdFase}} 
			
		});
		
		this.autorizacionesJson = null;
		//hacemos la llamada ajax para obtener la autorizacion de funcionalidades de usuarios
		Ext.Ajax.request(
		{
			url:'/autorizacion/gestionarLineasBase',
			//form:"[STICK FORM ID HERE]",
			method:'GET',
			scope : this,
			params: { idFase: this.myIdFase},
			
			async    : false,
			callback : function(opts, success, response) {	
				obj = Ext.decode(response.responseText);
				this.autorizacionesJson = obj.autorizacionesJson;
				
			}
			
		});
		
		
		
		
		this.Tblgrid = Ext.create('Ext.toolbar.Toolbar',{
			defaults: { hidden: true },
			items : [
				{
					xtype : 'button',
					id : this.idBtonCrearLineaBase,
					itemId : this.idBtonCrearLineaBase,
					text : 'Crear Linea Base',
					iconCls : 'icon_button_add',
					disabled : false,
					tooltip : 'Crea una linea base para los items de la fase',
					scope : this,
					hidden: this.autorizacionesJson.CREACION_LINEA_BASE,
					handler : this.CrearLineaBaseRecordSelect
				},
				{
					xtype : 'tbseparator'
				},
				{
					xtype : 'button',
					id : this.idBtonRomperLineaBase,
					itemId : this.idBtonRomperLineaBase,
					text : 'Romper Linea Base',
					iconCls : 'icon_button_edit',
					disabled : true,
					tooltip : 'Abre la linea base seleccionada',
					scope : this,
					hidden: this.autorizacionesJson.APERTURA_LINEA_BASE,
					handler : this.RomperLineaBaseRecordSelect
				},
				{
					xtype : 'tbseparator'
				},
				{
					xtype : 'button',
					id : this.idBtonVerItemsLineaBase,
					itemId : this.idBtonVerItemsLineaBase,
					text : 'Ver Items',
					iconCls : 'icon_button_delete',
					disabled : true,
					tooltip : 'Muestra los items en la linea base',
					hidden: this.autorizacionesJson.VER_ITEM_LINEA_BASE,
					scope : this,
					handler : this.VerItemsLineaBaseRecordSelect
				}
			]
		});
		
		this.grid = Ext.create(/*'Ext.grid.Panel'*/ 'GesLineasBaseLiveSearchGridPanel', {
			
			title: this.myNombreProyecto + ' | ' + this.myNombreFase + ' | ' + 'Lineas Base',
			frame : true,
			store : this.store,
			stripeRows : true,
			columnLines: true,
			loadMask : true,
			//width : 550,
			//height : 400,
			anchor: '100% 90%', 
			//features: [this.grouping],
			dockedItems : [this.Tblgrid,
				Ext.create('Ext.ux.StatusBar', {
				defaultText: this.defaultStatusText,
				name: 'searchStatusBar'
				})
			],
			columns: 
			[
				Ext.create('Ext.grid.RowNumberer'),
				{
					//text: 'id',
					hidden: true,
					dataIndex: 'idLineaBase',
					flex: 1
				},
				{
					text: 'Nro Items',
					dataIndex: 'nro_items',
					flex: 1
				},
				{
					text: 'Estado',
					dataIndex: 'estado',
					flex: 1
				},
				{
					text: 'Fecha Creacion',
					dataIndex: 'fecha_creacion',
					flex: 1
				}	
			],
			bbar: Ext.create('Ext.PagingToolbar', {
				store : this.store,
				displayInfo : true,
				displayMsg : 'Mostrando registros {0} - {1} de {2}',
				emptyMsg : "Sin registros para mostrar",
				
				doRefresh : function(){
					var store = this.store;
					store.loadPage(store.currentPage, 
						{
							params: 
							{
								idFase: store.idFase
							}
						}
					
					
					);
				},
				
			}),
			listeners:{
				scope:this,     	
				'selectionchange': function(view, records) {
					
					if(this.grid.getSelectionModel().getSelection()[0] != null){
						if(this.grid.getSelectionModel().getSelection()[0].data.estado == 'CERRADO' || this.grid.getSelectionModel().getSelection()[0].data.estado == 'REVISION'){
							Ext.getCmp(this.idBtonRomperLineaBase).setDisabled(false);
							Ext.getCmp(this.idBtonVerItemsLineaBase).setDisabled(false);
						}else{
							Ext.getCmp(this.idBtonRomperLineaBase).setDisabled(true);
							Ext.getCmp(this.idBtonVerItemsLineaBase).setDisabled(true);
						}
					}else{
						Ext.getCmp(this.idBtonRomperLineaBase).setDisabled(true);
						Ext.getCmp(this.idBtonVerItemsLineaBase).setDisabled(true);
					}
					
				}
				   
			}
			
		});
		
		this.items = [this.grid];
		this.callParent(arguments);
	},
	
	CrearLineaBaseRecordSelect: function(){
		
		
		var dsCmbItems = Ext.create('Ext.data.Store', {
			storeId: 'itemsStore',
			model : 'itemModel2',
			proxy: {
				type: 'ajax',
				url: '/lineas_base/itemsCrear',
				reader: {
					type: 'json',
					root: 'items'
				}
			},
			idFase: this.myIdFase,
			autoLoad : {params : {idFase: this.myIdFase}}
		});
		
		
		//ComboBox para mostrar items disponibles
		var cmbItems = Ext.create(/*'Ext.form.ComboBox'*/'Ext.ux.form.field.BoxSelect', {
						
			fieldLabel: 'Items',
			name : 'cmb_items',
			id: 'id_cmbx_items',
			displayField: 'nombreItem',
			width: 500,
			height : 70,
			store: dsCmbItems,
			queryMode: 'local',
			emptyText: 'Seleccione los items a insertar en la linea base',
			valueField: 'idItem',
			multiSelect :true,
			allowBlank : false,
			disabled: false
			
		});
		
		//Creamos el FormPanel que contendra los datos a importar
		this.FormCrearModal = Ext.create('Ext.form.Panel',{
			frame :true,
			title : 'Linea Base | ' + this.myNombreFase,
			bodyStyle :'padding:5px 5px 0',
			width : 550,
			height : 250,
			defaultType: 'textfield',
			items: [
					{	
						xtype : 'fieldcontainer',
						labelStyle : 'font-weight:bold;padding:0',
						items: [
							cmbItems
						]
					}
			],
			buttons: [{
				text : 'Guardar',
				id : 'id_btn_crear_lineabase',
				iconCls : 'icon_button_save',
				scope : this,
				handler : this.HandlerGuardarCrearLineaBase
				},{
				text : 'Cancelar',
				id : 'id_btn_cancelar_lineabase',
				iconCls : 'icon_button_cancel',
				scope : this,
				handler : function(){
					this.WindowFormCrearModal.close();
				}
			}]
		});
		
		//Una vez creado el FormPanel lo reseteamos
		this.FormCrearModal.getForm().reset();
		
		//Creamos la ventana que contendra el FormaPanel creado anteriormente
		this.WindowFormCrearModal = Ext.create('Ext.window.Window',{
			title : 'Crear Linea Base',
			bodyStyle : 'padding:10px 10px 10px 10px',
			region : 'center',
			width : 580,
			height : 300,
			modal : true,
			//resizable : false,
			draggable : false,
			closable : true,
			closeAction : 'destroy',
			items : [this.FormCrearModal]
		});
		
		//Mostramos la ventana con el formulario de edicion y los datos del registro seleccionado
		this.WindowFormCrearModal.show();
	},
	
	HandlerGuardarCrearLineaBase: function(){
		if (this.FormCrearModal.getForm().isValid()){
			var MyDate = new Date();
			MyDate = Ext.util.Format.date(MyDate,'d-F-Y');
			
			var rec = new lineabaseModel({
				fecha_creacion: MyDate
			});
			
			this.FormCrearModal.getForm().submit({
				method : 'POST',
				url : '/lineas_base/create', 
				clientValidation : true,
				scope : this,
				params : {
					idFase : this.myIdFase,
					ids_items : Ext.JSON.encode(Ext.getCmp('id_cmbx_items').getValue()),
					lineabase : Ext.JSON.encode(rec)
				},
				success: function(form, action){
						this.WindowFormCrearModal.close();
						this.store.load(
						{
							params:
							{
								idFase: this.myIdFase,
							}
						}
					);
				},
				failure: function(form, action){
					Ext.MessageBox.show({
						title : 'Info',
						msg : action.result.msg,
						buttons : Ext.MessageBox.OK,
						icon : Ext.MessageBox.INFO,
						width : 350
					});
				}
			});
		}
	},
	
	RomperLineaBaseRecordSelect: function(){
		Ext.MessageBox.show({
			title : "Información del sistema",
			msg : "¿Realmente desea romper la linea base seleccionada?",
			buttons : Ext.MessageBox.YESNO,
			icon : Ext.MessageBox.INFO,
			scope : this,
			fn : this.HandlerRomperLineaBase,
			width : 400
		});
	},
	
	HandlerRomperLineaBase: function(btn){
		if (btn == 'yes') { //btn=='yes'
			
			lineabaseSeleccionada = this.grid.getSelectionModel().getSelection()[0].data;
			Ext.Ajax.request({
				url : '/lineas_base/romper', 
				method : 'POST',
				scope : this,
				params : {
					idLineaBase : lineabaseSeleccionada.idLineaBase
				},
				success: function(response, opts) { //success
					var obj = Ext.JSON.decode(response.responseText);
					if(obj.success==true){
						this.store.load(
						{
							params:
							{
								idFase: this.myIdFase,
							}
						});
					}
					else if(obj.success==false){
						Ext.MessageBox.show({
							title : "Informacion del sistema",
							msg : obj.msg,
							buttons : Ext.MessageBox.OK,
							icon : Ext.MessageBox.ERROR,
							width : 400
						});
					}
					else{
						//this.WindowAdmUsuarios.el.unmask();
						Ext.MessageBox.show({
							title : "Informacion del sistema",
							msg : "Mensaje de error alternativo a la eliminacion del registro seleccionado",
							buttons : Ext.MessageBox.OK,
							icon : Ext.MessageBox.ERROR,
							width : 400
						});
					}
				}, //success
				failure: function(response, opts) { //failure
					//this.WindowAdmUsuarios.el.unmask();
					var obj = Ext.JSON.decode(response.responseText);
						Ext.MessageBox.show({
							title : "Informacion del sitema",
							msg : "Error de conexion al servidor de la base de datos",
							buttons : Ext.MessageBox.OK,
							icon : Ext.MessageBox.ERROR,
							width : 400
						});
				} //failure
			});
		}else{
	
		}
	},
	
	VerItemsLineaBaseRecordSelect: function(){
		lineabaseSeleccionada = this.grid.getSelectionModel().getSelection()[0].data;
		
		var dsCmbItems = Ext.create('Ext.data.Store', {
			storeId: 'itemsStore',
			model : 'itemModel2',
			proxy: {
				type: 'ajax',
				url: '/lineas_base/itemsVer',
				reader: {
					type: 'json',
					root: 'items'
				}
			},
			idLineaBase : lineabaseSeleccionada.idLineaBase,
			autoLoad : {params : {idLineaBase : lineabaseSeleccionada.idLineaBase}}
		});
		
		//grilla donde se van a mostrar los items de la linea base
		this.gridItems = Ext.create(/*'Ext.grid.Panel'*/ 'GesLineasBaseLiveSearchGridPanel', {
			
			title: 'Linea Base | Nro Items: ' + lineabaseSeleccionada.nro_items,
			frame : true,
			store : dsCmbItems,
			stripeRows : true,
			columnLines: true,
			loadMask : true,
			//width : 550,
			//height : 400,
			anchor: '100% 90%', 
			//features: [this.grouping],
			dockedItems : [
				Ext.create('Ext.ux.StatusBar', {
				defaultText: this.defaultStatusText,
				name: 'searchStatusBar'
				})
			],
			columns: 
			[
				{
					//text: 'id',
					hidden: true,
					dataIndex: 'idItem',
					flex: 1
				},
				{
					text: 'Código',
					dataIndex: 'codItem',
					flex: 1
				},
				{
					text: 'Nombre Item',
					dataIndex: 'nombreItem',
					flex: 1
				},
				{
					text: 'Complejidad',
					dataIndex: 'complejidadItem',
					flex: 1
				},
				{
					text: 'Version',
					dataIndex: 'versionItem',
					flex: 1
				},
				{
					text: 'Estado',
					dataIndex: 'estadoItem',
					flex: 1
				},
				{
					xtype: 'booleancolumn', 
					text: 'Revisar',
					trueText: 'SI',
					falseText: 'NO', 
					dataIndex: 'revisarItem'
				}
				
				
				
				
			],
			bbar: Ext.create('Ext.PagingToolbar', {
				store : dsCmbItems,
				displayInfo : true,
				displayMsg : 'Mostrando registros {0} - {1} de {2}',
				emptyMsg : "Sin registros para mostrar",
				doRefresh : function(){
					var store = this.store;
					store.loadPage(store.currentPage, 
						{
							params: 
							{
								idLineaBase : store.idLineaBase
							}
						}
					
					
					);
				},
				
			}),
			
		});
		
		//Creamos la ventana que contendra el FormaPanel creado anteriormente
		this.WindowFormVerItemsModal = Ext.create('Ext.window.Window',{
			title : 'Ver Items',
			bodyStyle : 'padding:10px 10px 10px 10px',
			region : 'center',
			width : 700,
			//height : 400,
			//autoWidth:true,
			autoHeight:true,
			modal : true,
			resizable : false,
			draggable : false,
			closable : true,
			closeAction : 'destroy',
			buttons: 
			[
				{
					text : 'Cancelar',
					id : 'id_btn_cancelar_verItems',
					//iconCls : 'icon_button_cancel',
					scope : this,
					handler : function(){
						this.WindowFormVerItemsModal.close();
					}
				}	
			],
			items : [this.gridItems]
		});
		//Mostramos la ventana con el formulario de edicion y los datos del registro seleccionado
		this.WindowFormVerItemsModal.show();
	}
});
